<?php

namespace App\ClickHouse\Models;

use App\ClickHouse\ClickHouseBase;

class ModelBase extends ClickHouseBase
{
    // 库名
    protected $database = 'sdk';

    protected $properties = [];

    const DEFAULT_VALUES = [
        'UInt32'  => 0,
        'UInt64'  => 0,
        'Float64' => 0,
        'String'  => '',
    ];

    // 返回属性
    public function getProperties()
    {
        return $this->properties;
    }

    // 判断数据是否某类型
    public function checkValueType($value, $type)
    {
        if ($value == '') {
            return true;
        }

        switch ($type) {
            case 'String':
                return is_string($value);
            case 'UInt32':
                $val = strval(intval($value));
                if ($val == strval($value)) {
                    return true;
                }
                break;
            case 'UInt64':
                $val = strval(intval($value));
                if ($val == strval($value)) {
                    return true;
                }
                break;
            case 'Float64':
                $val = strval(doubleval($value));
                if ($val == strval($value) || $val == $value) {
                    return true;
                }
                break;
        }

        return false;
    }

    public function getValueByType($value, $type)
    {
        switch ($type) {
            case 'String':
                return $value;
            case 'UInt32':
                return intval($value);
            case 'UInt64':
                return intval($value);
            case 'Float64':
                return doubleval($value);
        }

        return false;
    }

    /**
     * 组装数据，组装统一字段和格式用于待上传
     * 如果不存在某字段值，或者此值的类型不符合要求，则会使用系统默认值进行代替
     * 如果子类有自身一套方法可进行继承
     *
     * @param array $data
     * @return array
     */
    public function makeData($data)
    {
        $ret = [];
        foreach ($this->properties as $key => $type) {
            if (!isset($data[$key]) || !$this->checkValueType($data[$key], $type)) {
                $val = self::DEFAULT_VALUES[$type];
            } else {
                $val = $this->getValueByType($data[$key], $type);
            }
            $ret[] = $val;
        }

        return $ret;
    }
}
